package com.googlecode.recycled.xml;

import org.apache.commons.lang.UnhandledException;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.io.InputStream;

/**
 * Builder of org.w3c.dom.Document instances.
 */
public class DocumentBuilder {

    // CONFIGURATION STATE MEMBERS

    private boolean namespaceAware = false;

    // CONSTRUCTION

    protected DocumentBuilder() {
    }

    public static DocumentBuilder configure() {
        return new DocumentBuilder();
    }

    // QUICK BUILDERS

    public static Document newEmptyDocument() {
        return new DocumentBuilder().build(null);
    }

    public static Document newDocument(InputStream xml) {
        return new DocumentBuilder().build(xml);
    }

    public Document build(InputStream xml) {
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setNamespaceAware(namespaceAware);
            javax.xml.parsers.DocumentBuilder builder = factory.newDocumentBuilder();
            if (xml == null) {
                return builder.newDocument();
            }
            return builder.parse(xml);
        } catch (ParserConfigurationException e) {
            throw new UnhandledException(e);
        } catch (SAXException e) {
            throw new UnhandledException(e);
        } catch (IOException e) {
            throw new UnhandledException(e);
        }
    }

    public DocumentBuilder setNamespaceAware(boolean namespaceAware) {
        this.namespaceAware = namespaceAware;
        return this;
    }

}
